<template>
	<div>
		<quill-editor v-model="content" :options="editorOptions" ref="myQuillEditor" class="custom-quill-editor"></quill-editor>
	</div>
</template>

<script>
import Quill from 'quill'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import VueClipboard from 'vue-clipboard2'

VueClipboard.config.autoSetContainer = true

export default {
	data() {
		return {
			content: '',
			editorOptions: {
				// Your editor options here
				readOnly: true, // Set the editor to read-only mode
			},
		}
	},
	mounted() {
		this.addCopyButtons()
	},
	methods: {
		addCopyButtons() {
			const quill = this.$refs.myQuillEditor.editor.__quill
			console.log(quill.clipboard)
			quill.clipboard.addMatcher(Node.ELEMENT_NODE, (node, delta) => {
				if (node.tagName === 'PRE') {
					const code = node.textContent
					const copyButton = document.createElement('button')
					copyButton.textContent = 'Copy'
					copyButton.className = 'copy-code-btn'
					copyButton.addEventListener('click', () => {
						VueClipboard.toClipboard(code).then(() => {
							alert('Code copied to clipboard!')
						})
					})

					const pre = delta.ops[0].insert
					const range = delta.createRange(0, pre.length)
					const selection = quill.getSelection()
					const index = selection.index

					const block = quill.scroll.descendant(Quill.sources.API, index)[0]
					const offset = quill.scroll.offset(index)
					const [leaf] = quill.getLeaf(index)
					leaf.parent.domNode.insertBefore(copyButton, leaf.domNode.nextSibling)

					quill.setSelection(range, Quill.sources.SILENT)
				}

				return delta
			})
		},
	},
}
</script>

<style>
/* Your custom styles if needed */
.copy-code-btn {
	background-color: #fff;
	border: 1px solid #ccc;
	padding: 2px 8px;
	border-radius: 4px;
	cursor: pointer;
}
</style>
